import { BinaryViewElement } from "../index.js";
import { bufferToString, now } from "../util.js";
import { REQUESTS } from "./req/index.js";
import { RESPONSES } from "./res/index.js";
import { createWs } from "./Ws.js";

function main() {
    const main = document.createElement("div");
    document.body.appendChild(main);
    main.style.width = "100vw";
    main.style.height = "100vh";

    const bv = new BinaryViewElement();
    main.appendChild(bv);

    const ws = createWs();

    ws.addEventListener("message", (e) => {
        const buf = new Uint8Array(e.detail);
        bv.log(`${now()} 接收数据\n` + bufferToString(buf));
        bv.parse(buf);
    });

    ws.addEventListener("close", () => {
        bv.log(now() + " 连接关闭");
    });

    ws.addEventListener("open", () => {
        bv.log(now() + " 连接成功");
    });

    bv.setRequest(REQUESTS);
    bv.setResponse(RESPONSES);

    bv.addEventListener("submit", (e) => {
        if (!ws.connected) {
            bv.log("连接未建立，无法发送数据");
            return;
        }
        const { api: _, data } = e.detail;
        const buf = new Uint8Array(data);
        bv.log(`${now()} 发送数据\n` + bufferToString(buf));
        ws.send(buf);
    });
}

main();
